﻿namespace Jim.OA;

/// <summary>
/// OAWebService客户端
/// </summary>
public class OAWebServiceClient
{
    private readonly HrmServicePortTypeClient _service;
    private readonly string _ip;

    public OAWebServiceClient(string url,string ip) 
    {
        _service = new HrmServicePortTypeClient(0, url);
        _ip = ip;
    }

    /// <summary>
    /// 同步分部数据
    /// </summary>
    /// <param name="action"></param>
    /// <param name="dic"></param>
    /// <returns></returns>
    public async Task<SynSubCompanyResponse> SynSubCompany(string action, Dictionary<string, object> dic)
    {
        var requestData = XmlSerialize(action, dic, "org");
        var body = await _service.SynSubCompanyAsync(_ip, requestData);
        var result = XmlDeserialize<SynSubCompanyResponse>(body);
        if (!result.Message.Value.Equals("1")) throw new Exception(result.Message.Message);
        return result;
    }

    /// <summary>
    ///  查询分部列表
    /// </summary>
    /// <returns></returns>
    public async Task<SubCompanyBean[]> GetSubCompanyList()
    {
        var result = await _service.getHrmSubcompanyInfoAsync(_ip);
        return result;
    }

    /// <summary>
    /// 同步部门数据
    /// </summary>
    /// <param name="action"></param>
    /// <param name="dic"></param>
    /// <returns></returns>
    public async Task<SynDeptWebServiceResponse> SynDept(string action, Dictionary<string, object> dic)
    {
        var requestData = XmlSerialize(action, dic, "org");
        var body = await _service.SynDepartmentAsync(_ip, requestData);
        var result = XmlDeserialize<SynDeptWebServiceResponse>(body);
        if (!result.Message.Value.Equals("1")) throw new Exception(result.Message.Message);
        return result;
    }

    /// <summary>
    /// 查询部门列表
    /// </summary>
    /// <param name="subCompanyId"></param>
    /// <returns></returns>
    public async Task<DepartmentBean[]> GetDeptList(string subCompanyId = "")
    {
        var result = await _service.getHrmDepartmentInfoAsync(_ip, subCompanyId);
        return result;
    }


    /// <summary>
    /// 同步岗位
    /// </summary>
    /// <param name="action"></param>
    /// <param name="dic"></param>
    /// <returns></returns>
    public async Task<SynJobTitleResponse> SynJobTitle(string action, Dictionary<string, object> dic)
    {
        var requestData = XmlSerialize(action, dic, "jobtitle");
        var body = await _service.SynJobtitleAsync(_ip, requestData);
        var result = XmlDeserialize<SynJobTitleResponse>(body);
        if (!result.Message.Value.Equals("1")) throw new Exception(result.Message.Message);
        return result;
    }

    /// <summary>
    /// 查询岗位列表
    /// </summary>
    /// <param name="subCompanyId"></param>
    /// <param name="departmentId"></param>
    /// <returns></returns>
    public async Task<JobTitleBean[]> GetJobTitleList(string subCompanyId = "", string departmentId = "")
    {
        var result = await _service.getHrmJobTitleInfoAsync(_ip, subCompanyId, departmentId);
        return result;
    }



    /// <summary>
    /// 同步人员
    /// </summary>
    /// <param name="action"></param>
    /// <param name="dic"></param>
    /// <returns></returns>
    public async Task<SynEmpResponse> SynEmp(string action, Dictionary<string, object> dic)
    {
        var requestData = XmlSerialize(action, dic, "hrm");
        var body = await _service.SynHrmResourceAsync(_ip, requestData);
        var result = XmlDeserialize<SynEmpResponse>(body);
        if (!result.Message.Value.Equals("1")) throw new Exception(result.Message.Message);
        return result;
    }
    /// <summary>
    /// 查询职员列表
    /// </summary>
    /// <param name="workCode"></param>
    /// <param name="subCompanyId"></param>
    /// <param name="departmentId"></param>
    /// <param name="jobTitleId"></param>
    /// <param name="lastChangeDate"></param>
    /// <returns></returns>
    public async Task<UserBean[]> GetEmpList(string workCode = "", string subCompanyId = "", string departmentId = "", string jobTitleId = "", string lastChangeDate = "")
    {
        var result = await _service.getHrmUserInfoAsync(_ip, workCode, subCompanyId, departmentId, jobTitleId, lastChangeDate);
        return result;
    }

    /// <summary>
    /// 确认用户
    /// </summary>
    /// <param name="loginId"></param>
    /// <param name="password"></param>
    /// <returns></returns>
    public async Task<bool> CheckUser(string loginId = "", string password = "")
    {
        var result = await _service.checkUserAsync(_ip, loginId, password);
        return result;
    }

    /// <summary>
    /// 确认接口是否成功
    /// </summary>
    /// <returns></returns>
    public async Task<OACheckInvokeClientResponse> CheckInvokeClient()
    {
        var body = await _service.checkInvokeClientAsync();
        var result = body.FromJson<OACheckInvokeClientResponse>();
        if (!result.Code.Equals("1")) throw new Exception(result.Msg);
        return result;
    }


    /// <summary>
    /// 对象序列化成 XML String
    /// </summary>
    private string XmlSerialize(object obj)
    {
        string xmlString = string.Empty;
        System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(obj.GetType());
        using (MemoryStream ms = new MemoryStream())
        {
            xmlSerializer.Serialize(ms, obj);
            xmlString = Encoding.UTF8.GetString(ms.ToArray());
        }
        return xmlString;
    }

    /// <summary>
    /// 对象序列化成 XML String
    /// </summary>
    private string XmlSerialize(string action, Dictionary<string, object> dic, string nodeName)
    {
        List<string> list = new();

        foreach (var kv in dic)
        {
            list.Add($"<{kv.Key}>{kv.Value}</{kv.Key}>");
        }
        var xmlString = list.Join("");
        string xml = $"<?xml version=\"1.0\" encoding=\"UTF-8\"?><root><{nodeName}list><{nodeName} action=\"{action}\">{xmlString}</{nodeName}></{nodeName}list></root>";
        return xml;
    }


    /// <summary>
    /// XML String 反序列化成对象
    /// </summary>
    private T XmlDeserialize<T>(string xmlString)
    {
        System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
        using (Stream xmlStream = new MemoryStream(Encoding.UTF8.GetBytes(xmlString)))
        {
            using (XmlReader xmlReader = XmlReader.Create(xmlStream))
            {
                return (T)xmlSerializer.Deserialize(xmlReader);
            }
        }
    }

}
